package com.ahsjdy.st.stservice.service.impl;

import com.ahsjdy.st.stdao.entity.Rider;
import com.ahsjdy.st.stdao.mapper.RiderMapper;
import com.ahsjdy.stcommon.dto.RiderDTO;
import com.ahsjdy.stcommon.exception.BizException;
import com.ahsjdy.stcommon.holder.PageHolder;
import com.ahsjdy.stcommon.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @Author xuetao wang
 * @Date 2020/2/1
 */
@Service
public class RiderServiceImpl {

    @Autowired
    private RiderMapper riderMapper;

    public void add(String realName, String phone, String openId, String pictureName) {
        Rider rider = new Rider();
        rider.setCreateTime(new Date());
        rider.setModifyTime(rider.getCreateTime());
        rider.setOpenId(openId);
        rider.setPhone(phone);
        rider.setPictureUrl(pictureName);
        rider.setRealname(realName);
        rider.setStatus(0);
        riderMapper.insert(rider);
    }

    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(int riderId, int newStatus) {
        Rider rider = riderMapper.selectByPrimaryKey(riderId);
        if (rider.getStatus() == newStatus) {
            return;
        }

        int rows = riderMapper.updateStatus(rider.getId(), rider.getStatus(), newStatus);
        if (1 != rows) {
            throw new BizException("操作失败");
        }
    }

    public PageHolder listRiders(String realName,  String phone, int status, int currentPage, int pageSize) {
        int total = riderMapper.countRiders(realName, phone, status);
        PageHolder pageHolder = PageHolder.build(currentPage, total, pageSize);

        List<Rider> riders = riderMapper.listRiders(realName, status, phone, pageHolder.getOffset(), pageSize);
        List<RiderDTO> dtos = new ArrayList<>(riders.size());
        for (Rider rider : riders) {
            RiderDTO riderDTO = new RiderDTO();
            dtos.add(riderDTO);

            riderDTO.setCreateTime(DateUtils.dateToString(rider.getCreateTime(), "yyyy-MM-dd"));
            riderDTO.setId(rider.getId());
            riderDTO.setOpenId(rider.getOpenId());
            riderDTO.setPhone(rider.getPhone());
            riderDTO.setPictureUrl(rider.getPictureUrl());
            riderDTO.setRealname(rider.getRealname());
            riderDTO.setStatus(rider.getStatus());
        }

        pageHolder.setData(dtos);
        return pageHolder;

    }
}
